package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.PageResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.dto.HotArticleDTO;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.service.IArticleService;
import com.example.forum.service.IBoardService;
import com.example.forum.utils.RedisUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述:
 *
 * @author Lenovo
 * @date 2024/12/13
 */
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IBoardService boardService;

    @Resource
    private RedisUtil redisUtil;

    private static final String POST_LIMIT_KEY = "post_limit:";
    private static final int POST_WINDOW_SIZE = 3600; // 1小时窗口
    private static final int POST_LIMIT = 10; // 每小时最多发10帖

    /**
     * 发布帖子
     *
     * @param request
     * @param boardId
     * @param title
     * @param content
     * @return
     */
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @NonNull Long boardId,
                            @Validated String title,
                            @Validated String content) {
        if (!StringUtils.hasText(title) || !StringUtils.hasText(content)) {
            return AppResult.failed("输入不能为空");
        }

        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        String limitKey = POST_LIMIT_KEY + user.getId();

        // 检查是否被限流
        if (!redisUtil.isActionAllowed(limitKey, POST_WINDOW_SIZE, POST_LIMIT)) {
            return AppResult.failed("发帖太频繁,请稍后再试");
        }

        //校验用户是否被禁言
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //板块校验
        Board board = boardService.selectById(boardId.longValue());
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        //封装文章对象
        Article article = new Article();
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(user.getId());
        articleService.create(article);
        return AppResult.success();
    }

    /**
     * 查询每个版块下的帖子
     *
     * @param boardId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/getAllByBoardId")
    public AppResult<PageResult<Article>> getAllByBoardId(
            @RequestParam(value = "boardId", required = false) Long boardId,
            @RequestParam(value = "current", defaultValue = "1") long current,
            @RequestParam(value = "size", defaultValue = "10") long size) {

        PageResult<Article> pageResult;
        if (boardId == null) {
            pageResult = articleService.selectPage(current, size);
        } else {
            pageResult = articleService.selectPageByBoardId(boardId, current, size);
        }

        return AppResult.success(pageResult);
    }

    /**
     * 查看帖子详情
     *
     * @param request
     * @param id
     * @return
     */
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request, @RequestParam("id") @NonNull Long id) {
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //获取文章
        Article article = articleService.selectDetailById(id, user.getId());
        if (article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断是否为作者
        if (user.getId() == article.getUserId()) {
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    /**
     * 更新帖子
     *
     * @param request
     * @param id
     * @param title
     * @param content
     * @return
     */
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request, @RequestParam("id") @NonNull Long id,
                            @RequestParam("title") @Validated String title,
                            @RequestParam("content") @Validated String content) {
        if (!StringUtils.hasText(title) || !StringUtils.hasText(content)) {
            return AppResult.failed("输入不能为空");
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否被禁言
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //判断用户是否是作者

        Article article = articleService.selectById(id);
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        if (article.getState() == 1 || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        articleService.modify(id, title, content);
        log.info("更新成功，articleId: " + article.getId());
        return AppResult.success();
    }

    /**
     * 点赞
     *
     * @param request
     * @param id
     * @return
     */
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request, @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        boolean isLiked = articleService.thumbsUpById(id, user.getId());
        return AppResult.success(isLiked);
    }

    /**
     * 删除帖子
     *
     * @param request
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request, @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        Article article = articleService.selectById(id);
        //校验帖子状态
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断是否是作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        articleService.deleteById(id);
        return AppResult.success();
    }

    /**
     * 查询用户所属的帖子
     *
     * @param request
     * @param userId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/getAllByUserId")
    public AppResult getAllByUserId(HttpServletRequest request,
                                    @RequestParam(value = "userId", required = false) Long userId,
                                    @RequestParam(value = "current", defaultValue = "1") long current,
                                    @RequestParam(value = "size", defaultValue = "10") long size) {
        if (userId == null) {
            //从session中获取user信息
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        PageResult<Article> pageResult = articleService.selectPageByUserId(userId, current, size);
        return AppResult.success(pageResult);
    }

    @GetMapping("/search")
    public AppResult search(@RequestParam(value = "title") @Validated String title) {
        List<Article> articles = articleService.selectArticlesByTitleLike(title);
        if (articles == null) {
            articles = new ArrayList<>();
        }
        log.info("获取到： " + articles.size() + " 条搜索结果");
        return AppResult.success(articles);
    }

    @GetMapping("/getFeatured")
    public AppResult<List<HotArticleDTO>> getFeatured() {
        // 获取精华帖子列表(比如访问量最高的10篇)
        List<HotArticleDTO> featuredArticles = articleService.getFeaturedArticles();
        return AppResult.success(featuredArticles);
    }
}
